package medium;

import java.util.Objects;

public class L2 {


    public class ListNode {
      int val;
      ListNode next;
      ListNode() {}
      ListNode(int val) { this.val = val; }
      ListNode(int val, ListNode next) { this.val = val; this.next = next; }
    }

    class Solution {
        public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
            if (Objects.isNull(l1)) {
                return l2;
            }
            if (Objects.isNull(l2)) {
                return l1;
            }
            ListNode virHead = new ListNode();
            ListNode curNode = virHead;
            int remainder = 0;
            while (Objects.nonNull(l1) && Objects.nonNull(l2)) {
                int sum = l1.val + l2.val + remainder;
                remainder = sum / 10;
                curNode.next = new ListNode(sum % 10);
                curNode = curNode.next;
                l1 = l1.next;
                l2 = l2.next;
            }
            while (Objects.nonNull(l1)) {
                int sum = l1.val + remainder;
                remainder = sum / 10;
                curNode.next = new ListNode(sum % 10);
                curNode = curNode.next;
                l1 = l1.next;
            }
            while (Objects.nonNull(l2)) {
                int sum = l2.val + remainder;
                remainder = sum / 10;
                curNode.next = new ListNode(sum % 10);
                curNode = curNode.next;
                l2 = l2.next;
            }
            if (remainder != 0) {
                curNode.next = new ListNode(remainder);
            }
            return virHead.next;
        }
    }
}
